package com.purong.purong.fragment;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.purong.purong.R;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.LoadingDialog;
import com.yao.sdk.net.NetWorkListener;
import com.yao.sdk.net.ResponseInfo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/7/18.
 */
public abstract class BaseFragment extends NetFragment{
    private Map<String, BroadcastReceiver> receiverMap;
    public LoadingDialog mDialog;
    private String loadingUrl;
    private long dialogShowTime;
    private final long MIN_SHOW_TIME=500;
    private boolean hasDestory;
    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initBundle();
        if (rootView == null) {
            rootView = inflater.inflate(getRootViewId(), null);
            initView(rootView);
            initData();
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }
    public abstract int getRootViewId();
    public abstract void initView(View rootView);
    public abstract void initData();
    public void initBundle(){};

//    public  <T extends View> T $(View layoutView, int resId) {
//        return (T) layoutView.findViewById(resId);
//    }
    public boolean request(String url, Map<String, String> params, boolean addToken, NetWorkListener listener, boolean showDialog) {
        boolean isRequest=super.request(url, params,addToken? SharePreUtil.getInstance(getActivity()).getToken():null, listener);
        if (showDialog&&isRequest){
            if (mDialog==null){
                mDialog=new LoadingDialog(getActivity());
            }
            if (!hasDestroy())
            mDialog.show();
            dialogShowTime=System.currentTimeMillis();
            loadingUrl=url;
        }
        return isRequest;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hasDestory=false;
    }

    public boolean request(String url, Map<String, String> params, boolean addToken, boolean showDialog) {
        boolean isRequest=super.request(url, params, addToken?SharePreUtil.getInstance(getActivity()).getToken():null);
        if (showDialog&&isRequest){
            if (mDialog==null){
                mDialog=new LoadingDialog(getActivity());
            }
            if (!hasDestroy())
            mDialog.show();
            dialogShowTime=System.currentTimeMillis();
            loadingUrl=url;
        }
        return isRequest;
    }
    public boolean request(String url, Map<String, String> params,boolean addToken) {
        return super.request(url, params, addToken?SharePreUtil.getInstance(getActivity()).getToken():null);
    }
    public boolean requestNoToast(String url, Map<String, String> params, boolean addToken, boolean showDialog) {
        boolean isRequest=super.requestNoToast(url, params, addToken?SharePreUtil.getInstance(getActivity()).getToken():null);
        if (showDialog&&isRequest){
            if (mDialog==null){
                mDialog=new LoadingDialog(getActivity());
            }
            if (!hasDestroy())
                mDialog.show();
            dialogShowTime=System.currentTimeMillis();
            loadingUrl=url;
        }
        return isRequest;
    }
    public boolean requestNoToast(String url, Map<String, String> params,boolean addToken) {
        return super.requestNoToast(url, params, addToken?SharePreUtil.getInstance(getActivity()).getToken():null);
    }
    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (mDialog!=null&&mDialog.isShowing()&&responseInfo.url.equals(loadingUrl)){
            long time=System.currentTimeMillis()-dialogShowTime;
            if (time<MIN_SHOW_TIME){
                Timer timer=new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        mDialog.dismiss();
                    }
                },MIN_SHOW_TIME-time);
            }else {
                mDialog.dismiss();
            }

        }
        super.onResponse(responseInfo);
    }
    public void showToast(String toast) {
        Toast.makeText(getActivity(), toast, Toast.LENGTH_SHORT).show();
    }

    public void showToast(String toast, int length) {
        Toast.makeText(getActivity(), toast, length).show();
    }

    @Override
    public void onDestroy() {
        hasDestory=true;
        if (mDialog!=null&&mDialog.isShowing()){
            mDialog.dismiss();
        }
        destroyReceiver();
        super.onDestroy();
    }
    public void sendBroadcast(String action, String s) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra("String", s);
        getActivity().sendBroadcast(intent);
    }
    public void sendBroadcast(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        getActivity().sendBroadcast(intent);
    }
    public void sendBroadcast(String action, Serializable object) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra("object", object);
        getActivity().sendBroadcast(intent);
    }
    public void addAction(String action, BroadcastReceiver receiver) {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);
            getActivity().registerReceiver(receiver, filter);
            if (receiverMap==null){
                receiverMap=new HashMap<>();
            }
            receiverMap.put(action,receiver);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 销毁广播
     */
    public void destroyReceiver () {
        if (receiverMap != null) {
            BroadcastReceiver receiver ;
            for (String key : receiverMap.keySet()) {
                receiver =receiverMap.get(key);
                if (receiver != null) {
                    getActivity().unregisterReceiver(receiver);
                }
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public boolean hasDestroy(){
        return hasDestory;
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
//            return false;
//        if (getActivity().isDestroyed()){
//            return true;
//        }else {
//            return false;
//        }
    }
}
